package com.jch.udpdemo.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String msgStr = msg.content().toString(StandardCharsets.UTF_8);
        String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
        System.out.println(dateStr + " UDP服务端收到消息：" + msgStr);

        String sendMsg = "Hi I'm UDP Server !";
        byte[] bytes = sendMsg.getBytes(StandardCharsets.UTF_8);
        DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer(bytes),msg.sender());
        ctx.writeAndFlush(datagramPacket);
    }
}
